<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/22
 * Time: 10:26
 */

defined('BASEPATH') OR exit('No direct script access allowed');

require_once __DIR__ . '/Google/vendor/autoload.php';

class Google
{
    public function __construct()
    {

    }

function client($oauth = 0) 
{
	$client = new Google_Client();
	$client->setAuthConfig(__DIR__ . '/Google/client_secret.json');
	if ($oauth) {
		$client->setRedirectUri(base_url('GoogleApi/oauth2callback'));
	}
   	
   	$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
	return $client;
}

/**
 * Queries the Analytics Reporting API V4.
 *
 * @param service An authorized Analytics Reporting API V4 service object.
 * @return The Analytics Reporting API V4 response.
 */
function getReport($analytics) {

    // Replace with your view ID, for example XXXX.
    $VIEW_ID = "189115480";

    // Create the DateRange object.
    $dateRange = new Google_Service_AnalyticsReporting_DateRange();
    $dateRange->setStartDate("7daysAgo");
    $dateRange->setEndDate("today");

    // Create the Metrics object.
    $sessions = new Google_Service_AnalyticsReporting_Metric();
    $sessions->setExpression("ga:sessions");
    $sessions->setAlias("sessions");

    // Create the ReportRequest object.
    $request = new Google_Service_AnalyticsReporting_ReportRequest();
    $request->setViewId($VIEW_ID);
    $request->setDateRanges($dateRange);
    $request->setMetrics(array($sessions));

    $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
    $body->setReportRequests( array( $request) );
    return $analytics->reports->batchGet( $body );
}
}